articles

Home / DeveloperSection / Articles / Action Mode in Android

Action Mode in Android

Anonymous User6503 24-Feb-2015

Action mode allows the user to take actions on specific items in our user interface. Activating an ActionMode overtakes the system action bar with an overlay that includes menu options you provide and an extra option to exit the ActionMode. It also allows you to select multiple items at once on which to apply a single action.

 

Pre-Requisites:

1.       Ellipse SDK

2.       Android SDK

3.       ADT plugin


Or Android Studio and a compatible version of JAVA SDK

Install and configure the above utilities.

Now create a new Android project namely “ActionBarTest”.

Implementation objective:

To apply action mode on List view and implement multiple item sections and operations. 

Code Implementation: 

First of all update your menu_main. xml as follows:

 

<menu xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    tools:context=".MainActivity"> 

 

    <item

        android:id="@+id/edit"

        android:title="Edit"

        android:icon="@android:drawable/ic_menu_edit"

        android:orderInCategory="100"

        app:showAsAction="never" />

 

    <item

        android:id="@+id/delete"

        android:title="Delete"

        android:icon="@android:drawable/ic_menu_delete"

        android:orderInCategory="100"

        app:showAsAction="never" />

 

    <item

        android:id="@+id/selectAll"

        android:title="Select All"

        android:orderInCategory="100"

        app:showAsAction="never" />

 

</menu>

 Now navigate toMainActivity.java and add this code:

package com.example.msclient010.actionmodetest;

 

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.util.SparseBooleanArray;

import android.view.ActionMode;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.widget.AbsListView;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import java.util.ArrayList;

import java.util.List;

 

 

public class MainActivity extends ActionBarActivity implements AbsListView.MultiChoiceModeListener {

 

    //list of items

    List<String> items;

 

    //list view to show items

    private ListView mList;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        //creating a list view

        mList = new ListView(this);

 

        //adding items to list view

        items = new ArrayList<>();

        items.add("MindStick");

        items.add("Google");

        items.add("Facebook");

        items.add("Amazon");

        items.add("Microsoft");

 

 

 

        //creating an array adapter

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,items);

 

        //setting adapter to list view

        mList.setAdapter(adapter);

 

        //Set choice mode for list view

        mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

 

        //setting listener for multi choice select

        mList.setMultiChoiceModeListener(this);

 

        //set the list to main view

        setContentView(mList);

 

    }

 

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }

 

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

 

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);

 

    }

 

    @Override

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

        //You can do extra work here to update the menu if the

        //ActionMode is ever invalidated

        return true;

    }

 

    @Override

    public void onDestroyActionMode(ActionMode mode) {

        //This is called when the ActionMode has been exited

    }

 

    @Override

    public boolean onCreateActionMode(ActionMode mode, Menu menu) {

 

        MenuInflater inflater = mode.getMenuInflater();

        inflater.inflate(R.menu.menu_main, menu);

        return true;

    }

    @Override

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

        //List of checked item locations to do for the operations

        SparseBooleanArray myItems = mList.getCheckedItemPositions();

 

        //Switch on the item's ID to find the selected action

        switch (item.getItemId()){

            case R.id.edit:

                //Perform edit action

                break;

            case R.id.delete:

                //Perform edit actions

                break;

            case R.id.selectAll:

                //select all the items in the list

                for(String s : items)

                mList.setItemChecked(items.indexOf(s),true);

                break;

 

            default:

                return false;

 

        }

        return true;

    }

 

    @Override

    public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

       //count the number of checked items

        int count = mList.getCheckedItemCount();

 

       //set the title counting the no. of checked items

       mode.setTitle(String.format("%d Selected ", count));

 

    }

 

   

}

 

 Code Explanation: 

·   To use our ListView to activate a multiple selection ActionMode, we set its choiceMode attribute to CHOICE_MODE_MULTIPLE_MODAL. This is different from the traditional CHOICE_MODE_MULTIPLE, which will provide selection widgets on each list item to make the selection. The modal flag applies this selection mode only while an ActionMode is active.

·    There are a series of callbacks required to implement an ActionMode that are not built directly into an activity like the ContextMenu. We need to implement the ActionMode.Callback interface to respond to the events of creating the menu and selecting options. ListView has a special interface called MultiChoiceModeListener which is a sub interface of ActionMode.Callback

·   In onCreateActionMode(), we respond similarly to onCreateContextMenu(), just inflating our menu options for the overlay to display. Your menu does not need to contain icons; ActionMode can display the item names instead. The onItemCheckedStateChanged() method is where we will get feedback for each item selection. Here, we use that change to update the title of the ActionMode to display how many items are currently selected.

·    The onActionItemClicked() method will be called when the user has finished making selections and taps an option item. Because there are multiple items to work on, we go back to the list to get all the items selected with getCheckedItemPositions() so we can apply the selected operation.  

Running the application:

Hit on run button,

A list of companies will appear on screen.

Action Mode in Android

 

Now long press on any list item and the action mode will be activated, the action bar will be overlay the action option menu for the selected item

 

Action Mode in Android

 

Now let’s test the multi selection option, click on any other item, it will also get selected

 

 Action Mode in Android

 

Click on Select All, all the items will get selected.

Action Mode in Android 

 

Finally click on the left arrow and all the items will be unselected. 

Thanks for reading this post.

Happy Coding!!J

 


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By